import React,{ useEffect, useLayoutEffect, useState} from "react";
import {ethers} from "ethers";

import {contractABI , contractAddress} from "../utils/constants";

export const TransactionContext = React.createContext();

const {ethereum} = window;

const getEthereumContract = ()=>{
    const provider = new ethers.providers.Web3Provider(ethereum);
    const signer = provider.getSigner();
    const transactionsContract = new ethers.Contract(contractAddress, contractABI, signer);
    
    return transactionsContract;
}


export const TransactionProvider =( {children})=>{
    // const [transactions, setTransactions] = useState([]);
    // const [currentAccount, setCurrentAccount] = useState();

    const [currentAccount, setCurrentAccount] = useState('');
    const [isLoading,setIsLoading] = useState(false);
    const [formData, setFormData] = useState({addressTo:'', amount:'',keyword:'',message:''});
    const [transactionCount, setTransactionCount] = useState(localStorage.getItem('transactionCount'));
    const handleChange=(e, name) =>{
        setFormData((prevState)=>({...prevState,[name]:e.target.value}));
    }
    // 将状态返回到上一步

    const checkIfWalletIsConnected = async()=>{
        try {
            if (!ethereum) return alert("please install metamask");

            const accounts = await ethereum.request({ method: 'eth_accounts' });
            if (accounts.length) {
                setCurrentAccount(accounts[0]);
                // getAllTransactions



            } else {
                console.log('no accounts found')
            }
            
        } catch (error) {
            console.log(error);
        }
        
    }

    const connectWallet = async()=>{
        try {
            if (!ethereum) return alert("please install metamask");

            const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
            setCurrentAccount(accounts[0]);
            console.log(accounts);
        } catch (error) {
            console.log(error);
            throw new Error("no ethereum object");
        }
    }

    const sendTransaction = async()=>{
        try {
            if (!ethereum) return alert("please install metamask");
            const { addressTo, amount, keyword, message } = formData;
            const parseAmount = ethers.utils.parseEther(amount);

            const transactionsContract = getEthereumContract();
            await ethereum.request({ 
                method: 'eth_sendTransaction',
                params: [{
                    from:currentAccount,
                    to:addressTo,
                    gas:'0x5208',
                    value: parseAmount._hex,
                }]
            });
            
            const transactionHash = await transactionsContract.addToBlockchain(addressTo, parseAmount, message, keyword);

            setIsLoading(true);
            console.log(`loading -${transactionHash.hash}`);
            await transactionHash.wait();
            setIsLoading(false);
            console.log(`sucess - ${transactionHash.hash}`);
            const transactionsCount = await transactionsContract.getTransactionCount();

            setTransactionCount(transactionsCount.toNumber());
           

        } catch (error) {
            console.log(error);

            throw new Error("no ethereum object");
        }
    }

    useEffect(() =>{
        checkIfWalletIsConnected();
    },[]);

    return(
        <TransactionContext.Provider value={{connectWallet,currentAccount, formData, setFormData, handleChange, sendTransaction}}>
            {children}
        </TransactionContext.Provider>
    );
}